package com.gulimall.ssoserver.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Controller
public class LoginController {
    @Autowired
    StringRedisTemplate redisTemplate;
    //用户信息
    @ResponseBody
    @GetMapping("userinfo")
    public String userinfo(@RequestParam("token") String token){
        String s = redisTemplate.opsForValue().get(token);
        return s;
    }
    //远程未登录调用登录页面
    @GetMapping("login.html")
    public String login(@RequestParam("redirect_url") String url, Model model, @CookieValue(value = "login_cookie",required = false) String cooke){
        if(!StringUtils.isEmpty(cooke)){
            return "redirect:"+url+"?token="+cooke;
        }
        model.addAttribute("url",url);
        return "/login";
    }
    //处理登录逻辑
    @PostMapping("doLogin")
    public String doLogin(String username, String password, String url, HttpServletResponse response){
        if (!StringUtils.isEmpty(username)&& !StringUtils.isEmpty(password)){
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            redisTemplate.opsForValue().set(uuid,username);
            Cookie cookie = new Cookie("login_cookie",uuid);
            response.addCookie(cookie);
            return "redirect:"+url+"?token="+uuid;
        }
        return "/login";
    }
}
